package com.chen.project.white_jotter.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.project.white_jotter.mapper.AdminRoleMapper;
import com.chen.project.white_jotter.mapper.AdminUserRoleMapper;
import com.chen.project.white_jotter.mapper.UserMapper;
import com.chen.project.white_jotter.pojo.AdminUserRole;
import com.chen.project.white_jotter.pojo.User;
import com.chen.project.white_jotter.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private AdminRoleMapper adminRoleMapper;
    @Resource
    private AdminUserRoleMapper adminUserRoleMapper;

    @Resource
    private RedisUtil redisUtil;

    // 根据用户判断用户是否存在
    public boolean isExist(String username) {
        User user = getUserByUsername(username);
        return null != user;
    }

    // 通过用户名获取用户
    public User getUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }
    // 通过用户名+密码获取用户
    public User getUserByUsernameAndPassword(String username, String password) {
        return userMapper.selectUserByUsernameAndPassword(username, password);
    }

    ///////////////////////
    //// 后台界面的服务的 ////
    ///////////////////////

    // 获取一页用户
    public Map<String, Object> getPageUser(Integer pageNum, Integer pageSize){

        TreeMap<String, Object> userMap = new TreeMap<>();

        if(redisUtil.get("user_list_"+pageNum) != null){
            userMap = (TreeMap<String, Object>) redisUtil.get("user_list_"+pageNum);
        }
        else{
            Page<User> page = new Page<>(pageNum, pageSize);
            Integer count = userMapper.selectCount(null);

            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "username", "phone", "email", "enabled");

            List<User> userList = userMapper.selectPage(page, queryWrapper).getRecords();

            userList.forEach(item -> {
                // 查询用户的角色
                String role = adminRoleMapper.selectRoleNameByUserId(item.getId());
                item.setRole(role);
            });

            userMap.put("count", count);
            userMap.put("userList", userList);

            redisUtil.set("user_list_"+pageNum, userMap);
            redisUtil.expire("user_list_"+pageNum, 20L, TimeUnit.MINUTES);
        }
        return userMap;
    }

    // 添加新用户
    public int addUser(User user) {

        userMapper.insert(user);

        // 添加完用户，更新user-role表
        Integer userId = userMapper.selectUserIdByUsername(user.getUsername());
        AdminUserRole adminUserRole = new AdminUserRole();
        adminUserRole.setUid(userId);

        int i = adminUserRoleMapper.insert(adminUserRole);

        Set<String> keys = redisUtil.keys("user_list_*");
        redisUtil.delete(keys);

        return i;
    }

    // 更新用户状态
    public int updateUserStatus(User requestUser, Integer pageNum) {

        User user = userMapper.selectUserByUsername(requestUser.getUsername());
        user.setEnabled(requestUser.getEnabled());
        int i = userMapper.updateByPrimaryKeySelective(user);

        redisUtil.delete("user_list_"+pageNum);

        return i;
    }

    // 编辑用户信息
    public int editUser(User requestUser, Integer pageNum){

        requestUser.setEnabled(userMapper.selectByPrimaryKey(requestUser.getId()).getEnabled());
        int i = userMapper.updateByPrimaryKeySelective(requestUser);

        redisUtil.delete("user_list_"+pageNum);

        return i;
    }

    // 分配角色
    public int allotRole(Integer userId, Integer pageNum, Integer newRoleId) {

        int i = adminUserRoleMapper.updateRIdByUId(userId, newRoleId);

        redisUtil.delete("user_list_"+pageNum);

        return i;
    }

    // 删除用户
    public int remove(Integer id) {

        int i = userMapper.deleteByPrimaryKey(id);

        Set<String> keys = redisUtil.keys("user_list_*");
        redisUtil.delete(keys);

        return i;
    }
}
